package com.zenchn.util;


import com.zenchn.model.TSysFile;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * OtherUtils : 程序工具类，提供大量的便捷方法
 *
 * @author dxf
 * @since 2019-12-17 22:31
 */
public class OtherUtils {


    /**
     * 文件类型判断
     * @param sf
     * @return
     */
    public static String fileTypeJudge(TSysFile sf){
        if(sf.getFileType().contains("image")){
            return "static/fileType/image.png";
        }else{
            String suffix=sf.getFileName().substring(sf.getFileName().lastIndexOf('.')).toLowerCase();

            return  fileTypeJudge(suffix);
        }

    }

    /**
     * 文件类型判断
     * @param suffix
     * @return
     */
    public static String fileTypeJudge(String suffix){

        if(suffix.contains("doc") || suffix.contains("wps")){
            return "static/fileType/doc.png";
        }else if(suffix.contains("exe") || suffix.contains("msi")){
            return "static/fileType/exe.png";
        }else if(suffix.contains("htm")){
            return "static/fileType/html.png";
        }else if(suffix.contains("pdf")){
            return "static/fileType/pdf.png";
        }else if(suffix.contains("ppt")){
            return "static/fileType/ppt.png";
        }else if(suffix.contains("xls")){
            return "static/fileType/xls.png";
        }else if(suffix.contains("apk")){
            return "static/fileType/apk.png";
        }else if(suffix.contains("rar") || suffix.contains("zip")){
            return "static/fileType/zip.png";
        }else if(suffix.contains("txt") || suffix.contains("log")){
            return "static/fileType/txt.png";
        }else{
            return "static/fileType/other.png";
        }
    }

    /**
     * 去重
     * */
    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    /**
     * map正序排序
     * */
    public static Map<String,Object> sortMapByKey(Map<String, Object> map,Boolean isAsc) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, Object > sortMap;
        if(isAsc){
            sortMap = new TreeMap<>(new MapKeyComparatorAsc());
        }else{
            sortMap = new TreeMap<>(new MapKeyComparatorDesc());
        }
        sortMap.putAll(map);
        return sortMap;
    }

    static class MapKeyComparatorAsc implements Comparator<String> {
        @Override
        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }
    }

    static class MapKeyComparatorDesc implements Comparator<String> {
        @Override
        public int compare(String o1, String o2) {
            return o2.compareTo(o1);
        }
    }
}
